import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'
import useUserStore from '@/stores/user.js'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/s',
      name: 'layout',
      component: () => import('../layout/IndexLayout.vue'),
      children: [
        {
          path: '/home',
          name: 'home',
          component: () => import('../views/HomeView.vue'),
        },
        {
          path: '/addWorkLog',
          name: 'addWorkLog',
          component: () => import('../views/AddWorkLog.vue'),
        },
        {
          path: '/countByPerson',
          name: 'countByPerson',
          component: () => import('../views/CountByPerson.vue'),
        },
        {
          path: '/countByDept',
          name: 'countByDept',
          component: () => import('../views/CountByDept.vue'),
        },
        {
          path: '/countByDeptDetail',
          name: 'countByDeptDetail',
          component: () => import('../views/CountByDeptDetail.vue'),
        },
        {
          path: '/myWorkLog1',
          name: 'myWorkLog1',
          component: () => import('../views/MyWorkLog1.vue'),
        },
        {
          path: '/myWorkLog2',
          name: 'myWorkLog2',
          component: () => import('../views/MyWorkLog2.vue'),
        },
        {
          path: '/myWorkLog3',
          name: 'myWorkLog3',
          component: () => import('../views/MyWorkLog3.vue'),
        },
        {
          path: '/holidays',
          name: 'holidays',
          component: () => import('../views/HolidaysView.vue'),
        },
        {
          path: '/workbench',//
          name: 'workbench',//
          component: () => import('../views/WorkbenchView.vue'),
        },
        {
          path: '/my',
          name: 'my',
          component: () => import('../views/MyView.vue'),
        },
      ]
    }
  ]
})
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  if (to.name === 'login') {
    next()
  } else {
    const token = localStorage.getItem('token')
    if (token) {
      userStore.token = token
      if(!userStore.userInfo.userId){
        userStore.getUserInfo()
      }
      next()
    } else {
      next({ name: 'login' })
    }
  }
})
export default router
